package com.aurora.source.home.fragment;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aurora.source.R;
import com.aurora.source.base.BaseLazyFragment;
import com.aurora.source.base.PhotoViewActivity;
import com.aurora.source.entity.SysPermissionEntity;
import com.aurora.source.home.activity.VideoPlayActivity;
import com.aurora.source.home.adapter.ImgOrViderAdapter;
import com.aurora.source.home.bean.ContactUsDataBean;
import com.aurora.source.home.presenter.ContactUsPresenter;
import com.aurora.source.home.view.IContactUsView;
import com.aurora.source.util.DpPxUtil;
import com.aurora.source.util.GreenDaoHelper;
import com.aurora.source.util.SPUtils;
import com.aurora.source.widget.ItemDivider;
import com.aurora.source.widget.RxDialogSureCancel;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * @author: pipi
 * @description: 企业简介
 * @date: 2018/9/11
 * @version: 1.0
 */

public class EnterpriseProfileFragment extends BaseLazyFragment<ContactUsPresenter> implements IContactUsView {


    @BindView(R.id.et_enterprise_name)
    EditText etEnterpriseName;
    @BindView(R.id.et_enterprise_synopsis)
    EditText etEnterpriseSynopsis;
    @BindView(R.id.rv_recyclerView)
    RecyclerView rvRecyclerView;
    @BindView(R.id.ll_photograph)
    LinearLayout llPhotograph;
    @BindView(R.id.ll_ofVideo)
    LinearLayout llOfVideo;
    ImgOrViderAdapter imgOrViderAdapter;
    String companyId;//公司id
    @BindView(R.id.bt_sure)
    TextView btSure;
    Unbinder unbinder;
    @BindView(R.id.ll_up_pic_or_video)
    LinearLayout llUpPicOrVideo;
    private boolean updateCompany;


    @Override
    public void doLazyBusiness() {
        refreshUI();
    }

    @Override
    public void invisibleBusiness() {

    }

    @Override
    public ContactUsPresenter attach() {
        return new ContactUsPresenter(this);
    }

    @Override
    public int bindLayout() {
        return R.layout.enterpriseprofile;
    }

    @Override
    public void initData(@Nullable Bundle bundle) {
        SysPermissionEntity sysPermissionEntity = GreenDaoHelper.getDaoSession().getSysPermissionEntityDao().loadAll().get(0);
        updateCompany = sysPermissionEntity.getUpdateCompany();
    }

    /**
     * 刷新UI
     */
    public void refreshUI() {
        Map<String, String> params = new HashMap<>();
        params.put("querySource", "0");
        params.put("userId", (String) SPUtils.get(activity, SPUtils.USER_ID, ""));
        //    params.put("productId","");
        basePresenter.ContactUsSource(activity, params);
    }

    @Override
    public void initView(Bundle savedInstanceState, View contentView) {

        if(updateCompany){
            btSure.setVisibility(View.VISIBLE);
        }else {
            btSure.setVisibility(View.GONE);
        }

        imgOrViderAdapter = new ImgOrViderAdapter(activity);
        imgOrViderAdapter.setOnDeleteClickListener(new ImgOrViderAdapter.OnDeleteClickListener() {
            @Override
            public void onDeleteClick(final String resId, final int type) {
                final RxDialogSureCancel rxDialogSureCancel = new RxDialogSureCancel(activity);
                rxDialogSureCancel.setTitle("提示");
                rxDialogSureCancel.setContent("是否确认删除资源");
                rxDialogSureCancel.setSureListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        basePresenter.deleteCompanyResource(activity, type, companyId, resId);
                        rxDialogSureCancel.cancel();
                    }
                });
                rxDialogSureCancel.setCancelListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        rxDialogSureCancel.cancel();
                    }
                });
                rxDialogSureCancel.show();

            }
        });
        imgOrViderAdapter.setOnItemClickListener(new ImgOrViderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(String url, int type, int position) {
                Bundle bundle = new Bundle();

                if (type == 1) {
                    bundle.putString("title", "视频资源预览");
                    bundle.putString("url", url);
                    gotoActivity(VideoPlayActivity.class, bundle);
                    // PictureSelector.create(activity).externalPictureVideo(url);
                } else {
                    ArrayList<String> images = new ArrayList<>();
                    List<ContactUsDataBean.CompanyBannerDTOListBean> imgFiles = imgOrViderAdapter.getImgFiles();
                    for(ContactUsDataBean.CompanyBannerDTOListBean e:imgFiles){
                        images.add(e.getCompanyBannerPath());
                    }
                    bundle.putStringArrayList("images",images);
                    bundle.putString("title","图片资源预览");
                    bundle.putInt("position",position);
                    gotoActivity(PhotoViewActivity.class,bundle);
                }
            }
        });
        rvRecyclerView.setNestedScrollingEnabled(false);
        rvRecyclerView.setLayoutManager(new GridLayoutManager(activity, 4));
        rvRecyclerView.setAdapter(imgOrViderAdapter);
        rvRecyclerView.addItemDecoration(new ItemDivider().setDividerWith(DpPxUtil.dp2px(activity, 2)));

        if (!updateCompany) {
            enabledUI();
        }
    }

    //ui不能编辑
    private void enabledUI() {
       // btSure.setEnabled(false);
        llUpPicOrVideo.setVisibility(View.GONE);
        etEnterpriseSynopsis.setFocusable(false);
        etEnterpriseName.setFocusable(false);
        imgOrViderAdapter.setCanDelete(false);
    }

    @Override
    public void onContactUsSuccess(ContactUsDataBean data) {
        companyId = data.getCompanyId();
        etEnterpriseName.setText(data.getCompanyName());
        etEnterpriseSynopsis.setText(data.getCompanyContent());
        imgOrViderAdapter.setData(data.getCompanyBannerDTOList(), data.getCompanyVideoDTOList());
    }

    @Override
    public void onContactUsFail(String msg) {
        showToast(msg);
    }

    @Override
    public void onUpDataFail(String msg) {
        showToast(msg);
    }

    @Override
    public void onUpDataSuccess(String msg) {
        showToast(msg);
        refreshUI();
    }


    @OnClick({R.id.bt_sure, R.id.ll_photograph, R.id.ll_ofVideo})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_photograph:
                if (imgOrViderAdapter.getImgFiles().size() > 4) {
                    showToast("最多上传5张图片");
                    return;
                }
                showPictureSelector(1, true);//添加图片
                break;
            case R.id.ll_ofVideo:
                if (imgOrViderAdapter.getVideoFiles().size() > 0) {
                    showToast("最多上传一个视频文件");
                    return;
                }
                showVideoSelector(1);//添加视频
                break;
            case R.id.bt_sure:
                if(!updateCompany){
                    showToast("暂无修改权限");
                    return;
                }
                Map<String, String> params = new HashMap<>();
                params.put("companyId", companyId);
                params.put("companyName", etEnterpriseName.getText().toString());
                params.put("companyContent", etEnterpriseSynopsis.getText().toString());
                basePresenter.upDataCopInfo(activity, params);
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST: //图片
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //修改资质图片
                    Map<String, String> editParams = new HashMap<>();
                    editParams.put("updateType", "0");//0：图片;1:视频
                    editParams.put("companyId", companyId + "");
                    basePresenter.upDataCopImgOrVideo(activity, editParams, new File(selectList.get(0).getCutPath()), null);

                    break;

                case PictureConfig.REQUEST_CAMERA: //视频
                    // 图片、视频、音频选择结果回调
                    List<LocalMedia> selectList2 = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true  注意：音视频除外
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true  注意：音视频除外
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    //修改资质图片
                    File videoFile = new File(selectList2.get(0).getPath());
                    if(videoFile.exists()&&videoFile.isFile()){
                        long size = videoFile.length();
                        if( (double) size / 1048576>20){ //大于20M
                            showToast("视频文件大于20M，暂不支持");
                            return;
                        }
                    }else {
                        showToast("视频文件不存在");
                        return;
                    }
                    Map<String, String> editParams2 = new HashMap<>();
                    editParams2.put("updateType", "1");//0：图片;1:视频
                    editParams2.put("companyId", companyId + "");
                    Bitmap localVideoThumbnail = getLocalVideoThumbnail(selectList2.get(0).getPath());
                    basePresenter.upDataCopImgOrVideo(activity, editParams2, new File(selectList2.get(0).getPath()), localVideoThumbnail);

                    break;
            }
        }

    }


    /**
     * 获取本地视频的第一帧
     *
     * @param filePath
     * @return
     */
    public static Bitmap getLocalVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        //MediaMetadataRetriever 是android中定义好的一个类，提供了统一
        //的接口，用于从输入的媒体文件中取得帧和元数据；
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据文件路径获取缩略图
            retriever.setDataSource(filePath);
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        unbinder = ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }
}
